package com.summer.shopping.interceptor;

import com.summer.shopping.domain.common.req.ReqHolder;
import com.summer.shopping.domain.common.req.ReqInfo;
import com.summer.shopping.fun.handlers.userId.GetUserIdHandler;
import com.summer.shopping.utils.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;

@Component
@Slf4j
public class InBoundInterceptor implements HandlerInterceptor {


    @Autowired
    private GetUserIdHandler getUserIdHandler;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String uri = request.getRequestURI();
        String token = request.getHeader("token");
        ReqInfo reqInfo = new ReqInfo();
        if (token!=null && !token.equals("")){
            try {
                Long userId = getUserIdHandler.getUserIdByToken(token);
                Integer permission = getUserIdHandler.getPermissionByToken(token);
                reqInfo.setUserId(userId);
                reqInfo.setPermission(permission);
            } catch (Exception e){
                e.printStackTrace();
                log.info(uri+"解析令牌失败");
                response.sendError(ResultCodeEnum.JWT_EXPIRED.getCode(),ResultCodeEnum.JWT_EXPIRED.getMessage());
                return false;
            }
        }else{
            log.info(uri+"未登录,token为空");
//            reqInfo.setUserId(0L);
            response.sendError(ResultCodeEnum.NOTLOGIN.getCode(),ResultCodeEnum.NOTLOGIN.getMessage());
            return false;
        }
        ReqHolder.set(reqInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        response.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ReqHolder.set(null);
    }


}
